package workexp.alg.question;

import org.junit.Test;

public class MiddleNode {
      private static class ListNode {
         int val;
          ListNode next;
          ListNode() {}
          ListNode(int val) { this.val = val; }
          ListNode(int val, ListNode next) { this.val = val; this.next = next; }
      }

    public ListNode middleNode(ListNode head) {
          ListNode p1,p2;
          p1=head;
          p2=head;
          while(null!=p1.next){
              if(null!=p1.next.next){
                  p1=p1.next.next;
                  p2=p2.next;
              }else{
                  p1=p1.next;
                  p2=p2.next;
              }
          }
          return p2;

    }

    @Test
    public void test(){
        ListNode head = genList(new int[]{1, 2, 3, 4, 5, 6});
        ListNode node = middleNode(head);
        System.out.println(node.val);
    }

    private ListNode genList(int [] args){
        ListNode pre = null;
        ListNode head = null;
        for (int arg : args) {
            ListNode tmp = new ListNode();
            tmp.val=arg;
            if(pre!=null){
                pre.next=tmp;
            }else{
                head=tmp;
            }
            pre=tmp;
        }
        return head;
    }
}
